import logging
from functools import wraps

from apps.schemas import R
from models.models import User
from water_applets import settings

error_logger = logging.getLogger(settings.ERROR_LOG_NAME)


def set_request_user(func):
    """
    装饰器不能用，鉴权在装饰器之前执行。
    """

    def wrapper(request, *args, **kwargs):
        user = User.objects.filter(openid=request.headers.get("Openid")).first()
        request.user = user
        return func(request, *args, **kwargs)

    return wrapper


def handle_exception(error_msg):
    """
    处理异常
    :param error_msg: 出现异常时接口返回的错误信息
    :return:
    """

    def wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            try:
                try_result = func(*args, **kwargs)
                return try_result
            except Exception as e:
                error_logger.error(f"error occurred at {func.__name__}, error msg is {e}, parameter is {args} {kwargs}")
                return R.fail(error_msg)

        return inner

    return wrapper


def action_name(name=None, **kwargs):
    assert name is not None, (
        "@action_name() missing required argument: 'name'"
    )

    user_default = kwargs.get('user_default', False)

    def decorator(func):
        func.action_name = name
        func.user_default = user_default
        return func

    return decorator
